package com.bocloud.cmp.server.app.scheduler;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.cmp.entity.app.resource.OpenshiftCluster;
import com.bocloud.cmp.interfaces.app.resource.OpenshiftClusterService;
import com.bocloud.common.utils.ListTool;
import com.bocloud.coordinator.cache.LeaderShip;

/**
 * @author Zaney
 * @data:2017年4月26日
 * @describe:集群token守护进程
 */
public class OpenshiftClusterDaemon extends Thread {
	private static Logger logger = LoggerFactory.getLogger(OpenshiftClusterDaemon.class);
	private boolean stop = false;
	private boolean running = true;
	private OpenshiftClusterService openshiftClusterService;

	public OpenshiftClusterDaemon(OpenshiftClusterService openshiftClusterService) {
		super();
		this.openshiftClusterService = openshiftClusterService;
	}

	public void run() {
		while (running) {
			if (!stop) {
				try {
					Thread.sleep(1000 * 6 * 100 * 24);
				} catch (InterruptedException e) {
					logger.error("openshift cluster daemon is　intercepted", e);
					continue;
				}
				if (!LeaderShip.isLeader()) {
					if (logger.isDebugEnabled()) {
						logger.debug("I am not leader! skip this loop!");
					}
					continue;
				}
				try {
					// 查询所有的集群
					List<OpenshiftCluster> clusters = openshiftClusterService.getclusters();
					if (ListTool.isEmpty(clusters)) {
						if (logger.isDebugEnabled()) {
							logger.warn("no openshift cluster exist!");
						}
						continue;
					}
					// 获取服务端的token
					for (OpenshiftCluster cluster : clusters) {
						String token = openshiftClusterService.getToken(cluster.getProxyUrl());
						if (null != token && null != cluster.getToken()) {
							if (!cluster.getToken().equals(token)) {
								String[] fields = { "token" };
								cluster.setToken(token);
								openshiftClusterService.updateWithField(cluster, fields);
							}
						}
					}
				} catch (Exception e1) {
					logger.warn("openshift cluster Daemon Exception:", e1);
					continue;
				}
			}
		}
	}

	public void stopDeamon() {
		this.stop = true;
	}

	public void startDeamon() {
		this.stop = false;
	}

	public void shutdown() {
		this.running = false;
	}
}
